<?php

namespace ApiModule;

use \Nette\Application\JsonResponse;

use \Celebrio\Core\ServiceProvider;

use \ApplicationsModule\PeopleModule\PeopleManagement;
use \ApplicationsModule\PeopleModule\Person;

/**
 * @author     pavel
 * @package    Api
 */
class PeoplePresenter extends BasePresenter {

    /** @var string|array|mixed */
    private $json_response;

    /** @var \ApplicationsModule\PeopleModule\PeopleManagement */
    private $pm;

    public function startup() {
        parent::startup();

        if (!$this->getUser()->isLoggedIn()) {
            throw new \Exception("Can't access People API while not being logged in.");
        }

        $this->pm = new PeopleManagement();
    }

    public function actionAll() {
        $this->json_response = Person::more_to_a($this->pm->getAllPeople());
    }

    public function actionFriends() {
        $friends = $this->pm->getFriends();
        $this->json_response = Person::more_to_a($friends);
    }

    public function actionDetail($id) {
        $person = $this->pm->getPerson($id);
        if ($person === null) {
            $this->json_response = array("error" => "No such user");
        } else {
            $this->json_response = $person->to_a();
        }
    }

    public function beforeRender() {
        parent::beforeRender();
        $this->terminate(new JsonResponse($this->json_response));
    }
    
}